package com.duke.shaking.profile;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.duke.shaking.Constants;
import com.duke.shaking.MainActivity;
import com.duke.shaking.R;
import com.duke.shaking.ShakeTabActivity;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.utils.PhotoUtils;
import com.duke.shaking.utils.PrefUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class SetAvatarActivity extends TitleActivity implements OnItemClickListener {
	
	public static final String TAG = "SetAvatarActivity";

	private ImageView img_avatar;
	private TextView txtPhotosList;
	
	private Bitmap smallAvatar;
	private String photoPath;

	private GridView grid_photos;
	private ProgressDialog progress;
//	private UploadThread uploadThread;
	
	public SetAvatarActivity() {
	}

	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_set_avatar;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(0, //TITLE_BTN_EXIST | TITLE_BTN_BACK,
				R.string.back,
				TITLE_BTN_EXIST,
				R.string.done,
				R.string.title_set_avatar);
	}
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		img_avatar = (ImageView)findViewById(R.id.img_avatar);
		txtPhotosList = (TextView)findViewById(R.id.txt_photos_list);
		if (txtPhotosList != null) {
			int count;
			
			PrefUtils confPrefUtils = PrefUtils.getInstance(this, this.getString(R.string.configPref));
	        count = confPrefUtils.getInt(getString(R.string.conf_fakeMembers), MainActivity.initialMembersNum);
	        count /= 2;
	        
			String tip = String.format(Locale.CHINA,
					getString(R.string.tip_set_avatar_photos_list),
					count);
			txtPhotosList.setText(tip);
		}
		grid_photos = (GridView)findViewById(R.id.grid_photos);
		if (grid_photos != null) {
			grid_photos.setOnItemClickListener(this);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.i(TAG, "onResume");

		/*Log.i(TAG, "photo path: " + photoPath);
		if(photoPath == null) {
			photoPath = PrefUtils.getInstance(this, this.getString(R.string.registerPref)).getString("photoPath-" + me.getTelNo(), "");
			Log.i(TAG, "photo path from pref :" + photoPath);
		}
		if(photoPath != null && !photoPath.equals("")) {
			Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
			img_avatar.setImageBitmap(bitmap);
		}*/
	}

	@Override
	public void onRightBtn(View v) {
		
        // update photo
       /* AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(Throwable arg0, String arg1) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1);
				error("fail to upload photo, error:" + arg0.getMessage());
				error("fail to upload photo, arg1:" + arg1);
				dismissProgress();
				toast(R.string.err_upload_avatar);
				
			}

			@Override
			public void onSuccess(int arg0, String arg1) {
				// TODO Auto-generated method stub
				super.onSuccess(arg0, arg1);
				info("success to upload photo, status:" + arg0);
				info("photo url:" + arg1);
				dismissProgress();
				finish();
				go(ShakeTabActivity.class);
			}
        	
        };
        
        Map<String, String> params2 = new HashMap<String, String>();
        params2.put(NetUtils.TOKEN, me.getAuthToken());
        Log.i(TAG, "before uploading photo, photoPath: " + photoPath);
        params2.put(NetUtils.UPFILE, photoPath);
        AsyncHttpClient client = NetUtils.uploadPhoto(this, NetUtils.PHOTO_AVATAR, params2, responseHandler);
        if (client != null) {
        	showProgress(R.string.progress_upload_avatar, client, null);
        }*/
		uploadPhoto(photoPath, NetUtils.PHOTO_AVATAR);
	}
	
	private void uploadPhoto(final String photoPath, final int type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(NetUtils.TOKEN, me.getAuthToken());
		params.put(NetUtils.UPFILE, photoPath);
		//NetUtils.uploadPhoto(context, NetUtils.PHOTO_ALBUM, params, responseHandler);
		int msgId;
		if (type == NetUtils.PHOTO_AVATAR) {
			msgId = R.string.progress_upload_avatar;
		}
		else {
			msgId = R.string.progress_upload_photo;
		}
		/*uploadThread = new UploadThread(params, type);
		uploadThread.start();*/
		
		AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject object,
					AjaxStatus status) {
				Log.i(TAG, "JSONObject: " + object.toString());
				if(type == NetUtils.PHOTO_AVATAR) {
					me.setAvatarUrl(photoPath);
				}
				dismissProgressDlg();
				toast(R.string.set_avatar_successfully);
				finish();
				go(ShakeTabActivity.class);
			}

			@Override
			public void failure(int code, String message) {
				dismissProgressDlg();
				toast(R.string.err_upload_photo);
			}
			
		};
		showProgressDlg(msgId);
		NetUtils.uploadPhoto(this, type, params, ajaxCallback);
	}
	
	private void showProgressDlg(int msgId) {
		progress = new ProgressDialog(this);
		progress.setCanceledOnTouchOutside(false);
		progress.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				onCancelProgressDlg();
			}
			
		});
		
		if (!progress.isShowing()){
			progress.setTitle(null);
			progress.setMessage(getString(msgId));
			progress.setCancelable(true);
			progress.show();
		}
	}
	
	private void onCancelProgressDlg() {
		AjaxCallback.cancel();
		dismissProgressDlg();
	}
	
	private void dismissProgressDlg() {
		if(progress != null && progress.isShowing()) {
			progress.dismiss();
		}
	}
	
	@Override
	protected void onStop() {
		onCancelProgressDlg();
		super.onStop();
	}
	
	/*Handler handler2 = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (progress != null && progress.isShowing()) {
				progress.dismiss();
			}
			
			if(msg.what == 1) {
				toast(R.string.set_avatar_successfully);
				finish();
				go(ShakeTabActivity.class);
			}
			else {
				toast(R.string.err_set_avatar);
			}
		}
		
	};
	
	private class UploadThread extends Thread {
		private Map<String, String> params;
		private int type;
		
		public UploadThread(Map<String, String> params, 
				int type) {
			this.params = params;
			this.type = type;
			
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			String re = NetUtils.uploadPhoto(SetAvatarActivity.this, type, params);
			Message message = new Message();
			message.arg1 = type;
			if(re == null) {
				message.what = 0;
				toast(R.string.err_upload_photo);
			} else {
				message.what = 1;
				message.obj = re;
				//onUploadPhotoSuccess(re);
			}
			handler2.sendMessage(message);
			Log.i(TAG, "upload photo result: " + re);
		}
	}*/
	
	public void fetchPhoto(View view) {
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				switch(which) {
				case 0:
					//gotoGallery(null);
					gotoFetchPhoto(true);
					break;
				case 1:
					//gotoTakePhoto(null);
					gotoFetchPhoto(false);
					break;
				}
			}
		};
		
		new AlertDialog.Builder(this)
			.setTitle(R.string.title_select_photo_src)
			.setItems(R.array.item_dlg_select_photo_src, 
					listener)
			.show();
	}
	
	private void gotoFetchPhoto(boolean fromGallery) {
		Intent i = new Intent(this, ImageCropActivity.class);
		i.putExtra("fromGallery", fromGallery);
		startActivityForResult(i, Constants.INTENT_CODE_GET_AVATAR);
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		fetchPhoto(null);
	}
	
	public void gotoTakePhoto(View view) {
		//Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        //i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
		//startActivityForResult(i, Constants.INTENT_CODE_TAKE_PHOTO);
		gotoFetchPhoto(false);
	}

	public void gotoGallery(View view) {
		//Intent i = getGalleryPickIntent();
		//startActivityForResult(i, Constants.INTENT_CODE_FROM_GALLERY);
		gotoFetchPhoto(true);
	}
	
	protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
		info("onActivityResult, resultCode: " + resultCode
				+ ", requestCode: " + requestCode);
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		
		switch(requestCode) {
		case Constants.INTENT_CODE_GET_AVATAR:
			onGetAvatarResult(resultCode, intent);
			break;
		}
	}
	
	public void onGetAvatarResult(int resultCode, Intent intent) {
		Uri imgUri = intent.getData();
		if (imgUri == null) {
			toast(R.string.err_set_avatar);
			return;
		}
		
		String path = intent.getStringExtra("cropImagePath");
		if (path == null) {
			toast(R.string.err_set_avatar);
			return;
		}
		
		Bitmap bmp = PhotoUtils.loadImage(imgUri);
		if (bmp == null) {
			toast(R.string.err_set_avatar);
			return;
		}
		photoPath = path;
		showAvatar(bmp);
	}
	
	private Bitmap createSmallAvatar(Bitmap src) {
		/*return reduceBitmap(src, 
				dip2px(Constants.SmallImageWidth),
				dip2px(Constants.SmallImageHeight));*/
		
		return Bitmap.createScaledBitmap(src, 
				Constants.SmallAvatarWidth, 
				Constants.SmallAvatarHeight, 
				true);
	}
	
	protected void showAvatar(Bitmap bitmap) {

		// to save memory, 
		// we use the small size image
		smallAvatar = createSmallAvatar(bitmap);
		if (img_avatar != null) {
			img_avatar.setImageBitmap(smallAvatar);
			
		}
		
		// save image to file
		//photoPath = PhotoUtils.saveAvatar(smallAvatar, me.getTelNo());
		
		//PrefUtils.getInstance(this, this.getString(R.string.registerPref))
		//	.addString("photoPath-" + me.getTelNo(), photoPath);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		
		Log.i(TAG, "onConfigurationChanged");
		Log.i(TAG, "smallAvatar is null = " + (smallAvatar == null));
		if(smallAvatar != null) {
			img_avatar.setImageBitmap(smallAvatar);
		}
	}
	
	
}
